package com.ap.rabbitmq.component;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

/**
 * @Author: 逸尘风清
 * @Date: 2021/5/22
 * @Time: 16:29
 * 描述：
 */
@Component
public class RabbitmqSender {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 确认消息回调监听接口，用于确认消息是否被broker锁收到
     */
    final ConfirmCallback confirmCallback = new ConfirmCallback(){
        /**
         *
         * @param correlationData 作为一个唯一的标识
         * @param b broker是否落盘成功
         * @param s 失败的一下异常信息
         */
        @Override
        public void confirm(CorrelationData correlationData, boolean b, String s) {
            System.out.println("消息结果："+ b + " ,correlationData："+ correlationData.getId());
        }
    };

    /**
     * 对外发送消息的方法
     * @param message      具体的消息内容
     * @param properties   额外附加属性
     * @throws Exception
     */
    public void send(Object message, Map<String, Object> properties) throws Exception{
        MessageHeaders messageHeaders = new MessageHeaders(properties);
        // 构造消息
        Message<Object> msg = MessageBuilder.createMessage(message, messageHeaders);
        rabbitTemplate.setConfirmCallback(confirmCallback);

        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());

        MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public org.springframework.amqp.core.Message postProcessMessage(org.springframework.amqp.core.Message message) throws AmqpException {
                System.err.println("post to do :"+ message);
                return message;
            }
        };
        rabbitTemplate.convertAndSend("exchanger-1", "springboot.rabbit", msg, messagePostProcessor, correlationData);
    }
}
